<template>
  <t-card :bordered="false">
    <!-- 自定义搜索 -->
    <custom-search
      ref="customSearchRef"
      v-slot="{ params }"
      :default-params="{ isRead: '0' }"
      @submit="handleSeachTable"
    >
      <t-col :span="3">
        <t-form-item label="通知内容" name="message">
          <t-input v-model:value="params.message" clearable placeholder="" />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="通知类型" name="msgType">
          <t-select
            v-model:value="params.msgType"
            :options="dictionaryStore.get('message_type')"
            clearable
            filterable
            placeholder=""
          />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="楼盘名称" name="propertyName">
          <t-select v-model:value="params.propertyName" clearable filterable placeholder="">
            <t-option v-for="_ in propertyInfoList" :key="_.id" :value="_.id" :label="_.name">
              {{ _.name }}
              <span style="color: var(--td-text-color-secondary)">{{ _.address }}</span>
            </t-option>
          </t-select>
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="详细地址" name="address">
          <t-input v-model:value="params.address" clearable placeholder="" />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="是否阅读" name="isRead">
          <t-select
            v-model:value="params.isRead"
            :options="dictionaryStore.get('is_type')"
            clearable
            filterable
            placeholder=""
          />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="创建时间" name="createTime">
          <t-date-range-picker
            allow-input
            v-model:value="params.createTime"
            clearable
            enable-time-picker
            placeholder=" "
            style="width: 100%"
          />
        </t-form-item>
      </t-col>
    </custom-search>
    <!-- 自定义表格 -->
    <custom-table
      ref="customTableRef"
      v-model:selected-row-keys="selectedRowKeys"
      row-key="id"
      :columns="columns"
      :api="noticeListCRUD.page"
      column-controller-key="noticeList"
      :reserve-selected-row-on-paginate="true"
    >
      <template #topContent>
        <div style="margin-bottom: var(--td-comp-margin-xxl)">
          <!-- 阅读 -->
          <t-button
            v-if="selectedRowKeys.length"
            v-permission="['system:message-notify:batch-read']"
            @click="handleBatchRead"
          >
            阅读{{ selectedRowKeys.length }}）
          </t-button>
        </div>
      </template>
      <template #name="{ row }">
        <span :class="{ 'red-text': isTimeExpired(row.actualEndTime) }">
        {{ row.name }}
        </span>
        <div>
          <span v-if="row.payNumber">{{ chineseTranser(row.payNumber) }}期款</span>

          <span v-text="dictionaryStore.analysis('pay_status', row.payStatus)"></span>
          
        </div>
      </template>
      <template #engineeringStage="{ row }">
        {{ dictionaryStore.analysis('engineering_stage', row.engineeringStage) }}
      </template>
      <template #productStage="{ row }">
        {{ dictionaryStore.analysis('zheng_product_stage', row.productStage) }}
      </template>
      <template #orderStage="{ row }">
        {{ dictionaryStore.analysis('decoration_order_stage', row.orderStage) }}
      </template>
      <template #customerLevel="{ row }">
        {{ dictionaryStore.analysis('decoration_order_customer_level', row.customerLevel) }}
      </template>
      <template #propertyName="{ row }">
        {{ propertyInfoList.find((item) => item.id === row.propertyName)?.name }}
        <span style="color: gray;">{{ row.address }}</span>
      </template>
      <template #saleId="{ row }">
        {{ userStore.getUserNameById(row.saleId) }}
      </template>
      <template #designerId="{ row }">
        {{ userStore.getUserNameById(row.designerId) }}
      </template>
      <template #supervisionId="{ row }">
        {{ userStore.getUserNameById((row.supervisionId)) }}
      </template>
      <template #engineeringManagerId="{ row }">
        {{ userStore.getUserNameById(row.engineeringManagerId) }}
      </template>
      <template #productDesignerId="{ row }">
        {{ userStore.getUserNameById(row.productDesignerId) }}
      </template>
      <template #receiveUser="{ row }">
        {{ userStore.getUserNameById(row.receiveUser) }}
      </template>
      <template #msgType="{ row }">
        {{ dictionaryStore.analysis('message_type', row.msgType) }}
      </template>
      <template #isRead="{ row }">
        {{ dictionaryStore.analysis('is_type', row.isRead) }}
      </template>
      <template #createTime="{ row }">
        {{ dayjs(row.createTime).format('YYYY-MM-DD HH:mm:ss') }}
      </template>
      <template #isComplete="{ row }">
        <t-tag v-if="row.isComplete === '1'" theme="success" variant="light">
          {{ dictionaryStore.analysis('complete_type', row.isComplete) }}
        </t-tag>
        <t-tag v-if="row.isComplete === '0'" theme="warning" variant="light">
          {{ dictionaryStore.analysis('complete_type', row.isComplete) }}
        </t-tag>
      </template>
      <template #operation="{ row }">
        <t-space break-line>
          <!-- 查看订单 -->
          <view-order :id="row.orderId" :operate-type="row.operateType" :is-notice="true" />
          <!-- 阅读 -->
          <t-link v-if="row.isRead !== '1' && row.isComplete === '1'" theme="primary" @click="handleRead(row.id)">
            阅读
          </t-link>
          <!-- 转派工程部经理 -->
          <t-link theme="primary" v-if="row.engineeringId" v-permission="['system:engineering:update-engineering-manager']" @click="handleTransferEngineeringManager(row)">转派工程部经理</t-link>
           <!-- 转派监理 -->
           <t-link theme="primary" v-if="row.engineeringId" v-permission="['system:engineering:update-supervision']" @click="handleTransferSupervision(row)">转派监理</t-link>
        </t-space>
      </template>
    </custom-table>
    <transfer-engineering-manager :id="engineeringId" ref="transferEngineeringManager"
      @request-success="handleDialogRequestSuccess" />
    <transfer-supervision :id="engineeringId" ref="transferSupervision" @request-success="handleDialogRequestSuccess" />
  </t-card>
</template>

<script lang="ts">
export default {
  name: 'NoticeList',
};
</script>

<script setup lang="ts">
import dayjs from 'dayjs';
import { MessagePlugin, TableCol } from 'tdesign-vue-next';
import { onMounted, onUpdated, ref, useTemplateRef } from 'vue';

import { propertyManageCRUD } from '@/api/config/property';
import { batchRead, noticeListCRUD, read } from '@/api/notice/list';
import CustomSearch from '@/components/custom/search/index.vue';
import CustomTable from '@/components/custom/table/index.vue';
import ViewOrder from '@/pages/order/details/components/ViewOrder.vue';
import TransferEngineeringManager from '@/pages/project/engineering/components/TransferEngineeringManager.vue';
import TransferSupervision from '@/pages/project/engineering/components/TransferSupervision.vue';
import { useDictionaryStore, useUserStore } from '@/store';
import disposableParams from '@/utils/disposableParams';

// 用户仓库
const userStore = useUserStore();
// 字典仓库
const dictionaryStore = useDictionaryStore();
// 楼盘信息列表
const propertyInfoList = ref([]);
// 处理获取楼盘信息列表
const handleGetPropertyInfoList = () => {
  const params = {
    pageSize: -1,
  };
  propertyManageCRUD
    .page(params)
    .then((data) => {
      propertyInfoList.value = data.list;
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
};
handleGetPropertyInfoList();
// 选中行的keys
const selectedRowKeys = ref([]);
// 自定义搜索ref
const customSearchRef = useTemplateRef('customSearchRef');
// 自定义表格ref
const customTableRef = useTemplateRef('customTableRef');
// columns
const columns: TableCol[] = [
  { colKey: 'row-select', type: 'multiple', width: 50 },
  { colKey: 'engineeringStage', title: '施工阶段', width: 90 },
  { colKey: 'productStage', title: '产品阶段', width: 90 },
  { colKey: 'name', title: '客户名称', width: 130 },
  { colKey: 'customerLevel', title: '客户等级', width: 80 },
  { colKey: 'propertyName', title: '楼盘名称', width: 160 },
  { colKey: 'lastMessage', title: '最后回访内容', width: 200, ellipsis: true },
  { colKey: 'saleId', title: '客服', width: 80 },
  { colKey: 'designerId', title: '设计师', width: 80 },
  { colKey: 'productDesignerId', title: '产品设计师', width: 90 },
  { colKey: 'engineeringManagerId', title: '工程部经理', width: 90 },
  { colKey: 'supervisionId', title: '监理', width: 80 },
  { colKey: 'receiveUser', title: '接收人', width: 80 },
  
  { colKey: 'message', title: '通知内容', width: 200, ellipsis: true },
  { colKey: 'msgType', title: '通知类型', width: 80 },
  { colKey: 'isRead', title: '是否阅读', width: 80 },
  { colKey: 'createTime', title: '创建时间', width: 160 },
  { colKey: 'isComplete', title: '完成状态', width: 80, align: 'center', fixed: 'right' },
  { colKey: 'operation', title: '操作', width: 120, fixed: 'right' },
];
const handleSeachTable=(params:any) =>{
  disposableParams.set('to-do-tree-jump-params', {
    noticeIds: '',
  });
  handleInitTable()
}
// 处理初始化表格
const handleInitTable = () => {
  // 待办树跳转参数
  const toDoTreeJumpParams = disposableParams.get('to-do-tree-jump-params');
  const params = {
    ids: toDoTreeJumpParams.noticeIds,
    ...customSearchRef.value.params,
  };
  customTableRef.value.initTable(params);
};
// 处理刷新表格
const handleRefreshTable = () => {
  customTableRef.value.refreshTable();
};
onMounted(() => {
  handleInitTable();
});
onUpdated(() => {
  handleRefreshTable()
})
// 处理阅读
const handleRead = (id: number) => {
  const params = {
    id,
  };
  read(params)
    .then(() => {
      MessagePlugin.success('处理成功');
      handleRefreshTable();
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
};
// 处理批量阅读
const handleBatchRead = () => {
  const params = {
    ids: selectedRowKeys.value,
  };
  batchRead(params)
    .then(() => {
      MessagePlugin.success('处理成功');
      handleRefreshTable();
      selectedRowKeys.value = []
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
};
// 判断时间是否已过期（大于当前时间）
const isTimeExpired = (timeString:any) => {
  if(timeString) {
    return new Date(timeString) < new Date();
  }
};
// 转派工程部经理对话框ref
const transferEngineeringManagerDialogRef = useTemplateRef('transferEngineeringManager');
// 转派监理对话框ref
const transferSupervisionDialogRef = useTemplateRef('transferSupervision');
// 处理对话框请求成功
const handleDialogRequestSuccess = (result: Record<string, any>) => {
  if (result.mode === 'create') handleInitTable();
  if (result.mode === 'update') handleRefreshTable();
};
const engineeringId = ref()
// 处理转派工程部经理
const handleTransferEngineeringManager = (row: Record<string, any>) => {
  transferEngineeringManagerDialogRef.value.handleOpenDialog('update', row);
}
// 处理转派监理
const handleTransferSupervision = (row: Record<string, any>) => {
  engineeringId.value = row.engineeringId
  if (!row.engineeringManagerId) {
      MessagePlugin.error('请先选择转派工程部经理');
      return
    }
    transferSupervisionDialogRef.value.handleOpenDialog('update', row);
}
const chineseTranser = (num: number) => {
  const chineseNumbers = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
  return chineseNumbers[num] || num;
};
</script>

<style lang="less" scoped>
.red-text {
  color: red;
}
</style>
